<template>
  <div class="process-view">
    <!-- 顶部导航栏 -->
    <van-nav-bar
        title="处理"
        left-arrow
        @click-left="onClickLeft"
        fixed
    />

    <div class="process-form">
      <!-- 过程描述输入框 -->
      <div class="form-item">
        <div class="form-label">
          <span class="required">*</span>
          <span class="label-text">处理描述</span>
        </div>
        <van-field
            v-model="formData.handleone"
            type="textarea"
            placeholder="请输入描述"
            rows="4"
            required
        />
      </div>

      <!-- 附件上传 -->
      <div class="form-item">
        <div class="form-label">上传附件</div>
        <van-uploader
            v-model="fileList"
            multiple
            :max-count="6"
            :max-size="52428800"
            :before-read="beforeRead"
            :after-read="afterRead"
            @oversize="onOversize"
            @delete="onDelete"
        >
          <div class="upload-trigger">
            <van-icon name="plus" />
          </div>
        </van-uploader>
        <div class="upload-hint">{{ fileList.length }}/6</div>
        <div class="upload-tips">
          <p>1.维修记录字数限制500字。</p>
          <p>2.上传照片/视频总限制6张，</p>
          <p>图片最大限制50M,视频最大限制200M。</p>
        </div>
      </div>

      <!-- 底部按钮组 -->
      <div class="bottom-buttons">
        <van-button type="primary" block @click="handleProcess">确定</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { NavBar, Field, Uploader, Button, Toast, Icon } from 'vant';

export default {
  name: 'ProcessView',
  components: {
    [NavBar.name]: NavBar,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Button.name]: Button,
    [Icon.name]: Icon,
  },
  data() {
    return {
      formData: {
        handleone: '',        // 处理描述
        handleannexone: '',   // 附件，改为字符串类型
        handlestatus: 0,      // 处理状态
        handleshipping: ''    // 关联的工单ID
      },
      fileList: [],          // 新增：用于存储上传的文件列表
      updateData: {
        id: null,
        shippingstatus: 1     // 1表示已处理状态
      }
    }
  },
  methods: {
    onClickLeft() {
      this.$router.back()
    },
    // 文件上传前的校验
    beforeRead(file) {
      // 判断文件类型和大小
      if (file.type.includes('image/')) {
        if (file.size > 52428800) {
          Toast('图片大小不能超过50M');
          return false;
        }
      } else if (file.type.includes('video/')) {
        if (file.size > 209715200) {
          Toast('视频大小不能超过200M');
          return false;
        }
      } else {
        Toast('只能上传图片或视频文件');
        return false;
      }
      return true;
    },
    onOversize() {
      Toast('文件大小超出限制');
    },
    onDelete(file, detail) {
      const index = detail.index;
      // 将 handleannexone 字符串转为数组
      let annexArray = this.formData.handleannexone ? this.formData.handleannexone.split(',') : [];
      // 删除对应索引的 URL
      annexArray.splice(index, 1);
      // 重新组合为字符串
      this.formData.handleannexone = annexArray.join(',');
    },
    // 新增：文件上传后的处理
    afterRead(file) {
      const files = Array.isArray(file) ? file : [file];
      files.forEach((item) => {
        const formData = new FormData();
        formData.append('file', item.file);

        this.axios.post('http://localhost:9999/api-central-service/oss/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
            .then(res => {
              if (res.data) {
                // 初始化 handleannexone 为字符串
                if (!this.formData.handleannexone) {
                  this.formData.handleannexone = '';
                }
                // 将文件 URL 添加到字符串中，用逗号分隔
                this.formData.handleannexone = this.formData.handleannexone
                    ? this.formData.handleannexone + ',' + res.data
                    : res.data;
                Toast.success('文件上传成功');
              } else {
                Toast.fail('文件上传失败');
                const index = this.fileList.indexOf(item);
                if (index !== -1) {
                  this.fileList.splice(index, 1);
                }
              }
            })
            .catch(() => {
              Toast.fail('文件上传失败');
              const index = this.fileList.indexOf(item);
              if (index !== -1) {
                this.fileList.splice(index, 1);
              }
            });
      });
    },
    handleProcess() {
      if (!this.formData.handleone.trim()) {
        Toast('请输入处理描述');
        return;
      }

      // 确保所有文件都已上传完成
      if (this.fileList.length > 0 && (!this.formData.handleannexone ||
          this.formData.handleannexone.split(',').length !== this.fileList.length)) {
        Toast('请等待所有文件上传完成');
        return;
      }

      // 先添加处理记录
      this.axios.post('http://localhost:9999/api-central-service/shipping/handle', this.formData)
          .then(res => {
            if (res.data.code === 1) {
              // 添加成功后更新工单状态
              this.axios.post('http://localhost:9999/api-central-service/shipping/update', this.updateData)
                  .then(res => {
                    if (res.data.code === 1) {
                      Toast.success('处理成功');
                      setTimeout(() => {
                        this.$router.push('/ticket');
                      }, 1500);
                    } else {
                      Toast.fail(res.data.message || '状态更新失败');
                    }
                  })
                  .catch(() => {
                    Toast.fail('状态更新失败，请重试');
                  });
            } else {
              Toast.fail(res.data.message || '处理失败');
            }
          });
    }
  },
  mounted() {
    const id = this.$route.query.id;
    if (!id) {
      Toast('工单ID不能为空');
      this.$router.back();
      return;
    }
    this.updateData.id = id;
    this.formData.handleshipping = id;
  }
}
</script>

<style scoped>
.process-view {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
}

.process-form {
  padding: 16px;
}

.form-item {
  background: #fff;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 8px;
}

.form-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #323233;
}

.upload-trigger {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f7f8fa;
  border: 1px dashed #dcdee0;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #969799;
}

.upload-tips {
  margin-top: 12px;
  font-size: 12px;
  color: #969799;
  line-height: 1.5;
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 8px 16px;
  background: #fff;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.bottom-buttons .van-button {
  flex: 1;
  margin: 0 4px;
}

:deep(.van-field__control) {
  min-height: 100px;
}
</style>